<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/14/014
 * Time: 0:35
 */
namespace sms;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use think\facade\Log;

class Sms{
    private static $_instance = null;
    protected $accessKeyId;
    protected $accessSecret;
    protected $SignName;
    protected $TemplateCode;

    public function __construct()
    {
        $this->accessKeyId = config('sms.accessKeyId');
        $this->accessSecret = config('sms.accessSecret');
        $this->signName = config('sms.signName');
        $this->templateCode = config('sms.templateCode');
    }

    //单例模式
    public static function getInstance()
    {
        if (empty(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    //阿里大于发送短信
    function  send($phoneNum,$code){
        //return array('status'=>'success','msg'=>'','data'=>['Code'=>'OK']);
        AlibabaCloud::accessKeyClient($this->accessKeyId, $this->accessSecret)
            ->regionId('cn-hangzhou') // replace regionId as you need
            ->asDefaultClient();
        $param = json_encode(array('code'=>$code));
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->options([
                    'query' => [
                        'PhoneNumbers' => $phoneNum,
                        'SignName' => $this->signName,
                        'TemplateCode' =>$this->templateCode,
                        'TemplateParam' =>$param
                    ]
                ])
                ->request();
            if($result->Code != 'OK'){
                return array('status'=>'success','msg'=>$result->Message,'data'=>$result->toArray());
            }
            return array('status'=>'success','msg'=>'','data'=>$result->toArray());
        } catch (ClientException $e) {
            return array('status'=>'fail','msg'=>'短信发送失败','data'=>[]);
        } catch (ServerException $e) {
            return array('status'=>'fail','msg'=>'短信发送失败','data'=>[]);
        }
    }
}